const   MongoDB=require('mongodb'), 
  MongoClient = MongoDB.MongoClient,
  ObjectID = MongoDB.ObjectID,
  Config = require("./config");
 

class Db {
  static getInstance() {
    if (!Db.instance) {
      Db.instance = new Db();
    }
    return Db.instance;
  }

  constructor() {
    this.dbClient = ""; /* 属性DB对象 */
    this.connect(); /* 实例化的时候就链接数据库 */
  }
  //链接数据库
  connect() {
    let _that = this;
    return new Promise((resolve, reject) => {
      if (!_that.dbClient) {
        MongoClient.connect(
          Config.dburl,
          (err, client) => {
            if (err) {
              reject(err);
            } else {
              _that.dbClient = client.db(Config.dbName);
              resolve(_that.dbClient);
            }
          }
        );
      } else {
        resolve(_that.dbClient);
      }
    });
  }
  find(collecionName, json) {
    return new Promise((resolve, reject) => {
      this.connect().then(db => {
        // var result = db.collection(collecionName).find(json);
        db.collection(collectionName).find(json1,{fields:attr}).skip(slipNum).limit(pageSize)
        result.toArray(function(err, docs) {
          if (err) {
            reject(err);
            return;
          }
          resolve(docs);
        });
      });
    });
  }
  update(collectionName, json1, json2) {
    return new Promise((resolve, reject) => {
      this.connect().then(db => {
        //db.user.update({},{$set:{}})
        db.collection(collectionName).updateOne(
          json1,
          {
            $set: json2
          },
          (err, result) => {
            if (err) {
              reject(err);
            } else {
              resolve(result);
            }
          }
        );
      });
    });
  }
  insert(collecionName, json) {
    return new Promise((resolve, reject) => {
      this.connect().then(db => {
        db.collection(collecionName).insertOne(json, function(err, result) {
          if (err) {
            reject(err);
          } else {
            resolve(result);
          }
        });
      });
    });
  }
  remove(collecionName, json) {
    return new Promise((resolve, reject) => {
      this.connect().then(db => {
        db.collection(collecionName).removeOne(json, function(err, result) {
          if (err) {
            reject(err);
          } else {
            resolve(result);
          }
        });
      });
    });
  }
  getObjectId(id) {
    return new ObjectID(id);
  }
}

module.exports = Db.getInstance();
